﻿namespace SampleApp.Tests.Pages {
    using System;
    using Microsoft.Services.TestTools.UITesting.Html;
    using Microsoft.VisualStudio.TestTools.UITesting.HtmlControls;

    [EntryUri("/Products")]
    public class Products : Page {

        public Products EnsureAtLeastOneCategory() {

            var categories = Page.Launch<Categories>();
            bool exists = categories.CategoriesExists();
            if (!exists) {
                categories
                    .NavigateToCreateCategory()
                    .CreateNewCategory(DateTime.Now.Ticks.ToString());
            }
            categories.Close();

            return this;
        }

        public bool ProductsExists() {
            return Browser
                .Find<HtmlTable>()
                .RowCount > 1;
        }

        public ProductsCreate NavigateToCreateProduct() {
            Browser.ClickOnLink("Create New");
            return NavigatedTo<ProductsCreate>();
        }

        public bool ListContainsName(string name) {
            return Browser.Find<HtmlCell>(new { InnerText = name }).Exists;
        }

        public string ProductNameOnRow(int row) {
            return ValueInCell(row, 1);
        }

        public string CategoryOnRow(int row) {
            return ValueInCell(row, 4);
        }

        private string ValueInCell(int row, int column) {
            return Browser
                .Find<HtmlTable>()
                .GetValueInCell(row, column);
        }

        public ProductDetails ClickOnProductDetailsOnRow(int row) {
            Browser
                .Find<HtmlCell>()
                .Filter(new {
                    RowIndex    = row.ToString(),
                    ColumnIndex = "0"
                })
                .Find<HtmlHyperlink>()
                .Instance(2)
                .Click();
            return NavigatedTo<ProductDetails>();
        }
    }
}